<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\roomService;
use app\service\roominfoService;
use think\Db;
use think\Exception;
use think\Log;
class Wxuser extends Common{
   
    //下拉菜单
    public function fetchdata() {
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community_id = request()->post('community_id');
                $group = array_unique((new roominfoService())->groupList($community_id));
                return array_values($group);
            case 2:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = array_unique((new roominfoService())->buildingList($community_id,$group));
                return array_values($building);
            case 3:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new roominfoService())->unitList($community_id,$group,$building));
                return array_values($unit);
            case 4:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new roominfoService())->roomList($community_id,$group,$building,$unit));
                return array_values($room);
            default:
                return json(['info' => '查询错误']);
        }
    }

    public function userList(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        //Log::write($communitylist,"community");
        $community_id = $com['community_id'];
        $this->assign('communitylist',$communitylist);
        //查询
        $data = request()->get();
        // dump($data);exit();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            $this->assign('groups', array_values($groups));

        }
        $where=array();
        //var_dump($data);
        if (!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }



            if(!empty($data['name1'])){
                $where['name'] = $data['name1'];//姓名
            }else{
                $where['name'] = "";
            }
            if(!empty($data['phone'])){
                $where['phone'] = $data['phone'];//电话
            }else{
                $where['phone'] = "";
            }
            $this->assign('where',$where);   

        }
        $where = array_filter($where);
        //var_dump($where);die;
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);

        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数

        $number = Db::name('wxuser')->where('community_id', 'in', $community_id)->where($where)->count();

        $this->assign('number',$number);
        //查询房屋信息
        $userlist = Db::name('wxuser')->where('community_id', 'in', $community_id)->where($where)->order('id asc')->paginate(100, false, [
            'page'  =>  $page,
            'query' =>  $where
        ]);
        foreach ($userlist as $key => $value) {
            
        }
        if($number!="0"){

        }else{

        }
        $this->assign('list',$userlist);
        
        $this->assign('userlist',$userlist);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('user_list');
    }
    //
    public function userAdd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        $this->assign('communitylist',$communitylist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            $communityinfo=Db::table("community")->where("id",$data["community_id"])->find();

            /*//判断房屋是否重复
            $info = Db::name('wxuser')
                ->where('phone',$data["phone"])
                ->find();
            if($info){
                $this->error('手机号已存在');
            }*/
            $data['community_name']=$communityinfo["name"];
            $data['create_time'] =$data['update_time'] = time();
            //将数据插入数据库
            $last_id = Db::name('wxuser')->insertGetId($data);
            //判断数据是否插入成功
            if($last_id){
                $bind_code=str_pad($last_id,5,0,STR_PAD_LEFT);
                Db::table("wxuser")->where("id",$last_id)->update(["bind_code"=>$bind_code]);

                $devicelist1=Db::table("device")
                    ->where("community_id",$data["community_id"])
                    ->where("devicetype",1)
                    ->select();//大门
                $devicelist2=Db::table("device")
                    ->where("devicetype",2)
                    ->where("community_id",$data["community_id"])
                    ->where("group",$data["group"])
                    ->where("building",$data["building"])
                    ->where("unit",$data["unit"])
                    ->select();
                $devicelist3=Db::table("device")
                    ->where("devicetype",3)
                    ->where("community_id",$data["community_id"])
                    ->where("group",$data["group"])
                    ->where("building",$data["building"])
                    ->where("unit",$data["unit"])
                    ->select();
                $devicelist=array_merge($devicelist1,$devicelist2,$devicelist3);
                foreach ($devicelist as $info){
                    $map['wxuser_id'] = $last_id;
                    $map['deviceid'] = $info["id"];
                    $res=Db::table("wxuser_device")->where($map)->find();
                    if(empty($res)){
                        Db::table('wxuser_device')->insert([
                            "wxuser_id" =>$last_id,
                            "deviceid" =>$info["id"],
                            "create_time" =>time(),
                            "update_time" =>time()
                        ]);
                    }
                }

                //进行设备授权
                $this->success('添加成功',url('userAdd'));
            }else{
                $this->error('添加失败',url('userAdd'));
            }
        }else{
            return $this->fetch('user_add');
        }
    }

    public function deviceauth(){
        if(request()->isPost()){
            $wxuser_id = request()->param("wxuser_id");
            $deviceids = request()->param("deviceids");
            Db::startTrans();
            try{
                Db::table('wxuser_device')->where("wxuser_id",$wxuser_id)->delete();
                $deviceidarr = explode("," ,$deviceids);
                foreach ($deviceidarr as $id){
                    Db::table('wxuser_device')->insert([
                        "wxuser_id" =>$wxuser_id,
                        "deviceid" =>$id,
                        "create_time" =>time(),
                        "update_time" =>time()
                    ]);
                }
                // 提交事务
                Db::commit();
                return json(["code"=>0]);

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["code"=>1,"errmsg"=>$e->getMessage()]);
            }
        }else{
            $wxuser_id= request()->get("id");
            $idarr = array();
            $wxuser_devicelist = Db::table("wxuser_device")->where("wxuser_id",$wxuser_id)->select();
            foreach ($wxuser_devicelist as $info){
                $idarr[] = $info["deviceid"];
            }
            $devicelist=Db::table("device")->select();
            $this->assign('devicelist',$devicelist);
            $this->assign('wxuser_id',$wxuser_id);
            $this->assign('idarr',$idarr);
            return $this->fetch();
        }
    }

    public function deviceaccredit(){
        $wxuser_id = request()->param("wxuser_id");
        $deviceids = request()->param("deviceids");
        Db::startTrans();
        try{
            Db::table('wxuser_device')->where("wxuser_id",$wxuser_id)->delete();
            $deviceidarr = explode("," ,$deviceids);
            foreach ($deviceidarr as $id){
                Db::table('wxuser_device')->insert([
                    "wxuser_id" =>$wxuser_id,
                    "deviceid" =>$id,
                    "create_time" =>time(),
                    "update_time" =>time()
                ]);
            }
            // 提交事务
            Db::commit();
            return "提交成功";
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        var_dump($wxuser_id,$deviceids);
    }
        //修改小区房屋信息
    public function userEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['community_id']);
        $communitylist = (new roomService())->communityList($where);
        $this->assign('communitylist',$communitylist);
        
        if(request()->isGet()){
            $id = request()->param('id');
            if(!isset($id) && empty($id)){
                $this->error('房屋不存在');
            }
            //查询房屋数据
            $info = (new roominfoService())->roominfoIdList($id);
            $this->assign('info',$info);
            return $this->fetch('room_edit');
        }else{
            //获取表单数据
            $data = request()->post();
            $info["name"]=$data["name"];
            $info["phone"]=$data["phone"];
            //$info["room"]=$data["room"];
            $info["id"]=$data["id"];

            //将修改的数据插入数据库
            $result = (new roominfoService())->roominfoEdit($info);
            //判断数据是否插入成功
            if($result){
                $this->success('修改房屋信息成功',url('roominfolist'));
            }else{
                $this->error('修改房屋信息失败',url('roominfoEdit'));
            }
        }
    }

    public function userDel(){
        $id=request()->get("id");

        $userinfo=Db::table("wxuser")->where("id",$id)->find();
        if(empty($userinfo)){
            return json(['errMsg' => '该用户不存在']);
        }


            Db::startTrans();
            $res1 = Db::table("wxuser")->where("id",$id)->delete();
            $res2 =Db::table("wxuser_device")->where("wxuser_id",$id)->delete();
            Db::commit();
            $this->success('删除成功',url('userList'));



    }
    public function userDelAll(){
        $validate = $this->validate(request()->param(),[
			'id'	=>	'require'
		]);
		if($validate !== true){
			$this->error($validate);
        }
        $id = request()->param('id');
        if (strpos($id, ',')) {
            $arr = explode(',', $id);
            $info = Db::name('wxuser')->where('id', 'in', $arr)->select();;
            if (count($info) != count($arr)) {
                return json(['info' => '用户信息不完整']);
            }
            foreach($info as $inf){
                //判断房屋下是否有人员是否能删除
                $userinfo=Db::table("personnel")->where("room_id",$inf["id"])->find();
                if(!empty($userinfo)){
                    return json(['info' => '请先删除该房屋下的用户']);
                }

                $result =  (new roomService())->roomDel($inf['id']);  
            }
        }else{
            //判断是否存在该数据
            $info = (new roomService())->roomId($id);
            if(empty($info)){
                $this->error('该房屋不存在');
            }
            $userinfo=Db::table("personnel")->where("room_id",$id)->find();
            if(!empty($userinfo)){
                return json(['info' => '请先删除该房屋下的用户']);
            }
            $result =  (new roomService())->roomDel($id);
        }
        if($result){
            $this->success('删除成功',url('roomList'));
		}else{
            $this->success('删除失败',url('roomList'));
		}
    }
    //通过Excel批量添加房屋信息 
    public function userExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' || $extension =='xls') {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    $data['community_name']=$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
                    $communityinfo=Db::table("community")->where("name",$data['community_name'])->find();
                    if(empty($communityinfo)){
                        echo "第".$j."小区名称不存在<br/>";
                        exit;
                    }
                    $data["community_id"]=$communityinfo["id"];
                    $data['group']=$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
                    $data['building']=$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
                    $data['unit']=$objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();
                    $data['room']=$objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();
                    $data['wiegand']=$objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();
                    //业主姓名
                    $data['name'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();
                    //业主电话
                    //$data['phone'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();

                    $data['create_time'] = time();
                    $data['update_time'] = time();

                    $data = array_filter($data);
                    $number = count($data);
                    $numbers = 10;
                    if($number == $numbers){
                        //数据插入到数据库并返回主键id
                        for($i=0; $i<5; $i++){
                            //判断房屋是否重复
                            $last_id = Db::table("wxuser")->insertGetId($data);
                            //判断数据是否插入成功
                            if ($last_id) {
                                $bind_code=str_pad($last_id,5,0,STR_PAD_LEFT);
                                Db::table("wxuser")->where("id",$last_id)->update(["bind_code"=>$bind_code]);
                                $devicelist1=Db::table("device")
                                    ->where("community_id",$data["community_id"])
                                    ->where("devicetype",1)
                                    ->select();//大门
                                $devicelist2=Db::table("device")
                                    ->where("devicetype",2)
                                    ->where("community_id",$data["community_id"])
                                    ->where("group",$data["group"])
                                    ->where("building",$data["building"])
                                    ->where("unit",$data["unit"])
                                    ->select();
                                $devicelist3=Db::table("device")
                                    ->where("devicetype",3)
                                    ->where("community_id",$data["community_id"])
                                    ->where("group",$data["group"])
                                    ->where("building",$data["building"])
                                    ->where("unit",$data["unit"])
                                    ->select();
                                $devicelist=array_merge($devicelist1,$devicelist2,$devicelist3);
                                foreach ($devicelist as $info){
                                    $map['wxuser_id'] = $last_id;
                                    $map['deviceid'] = $info["id"];
                                    $res=Db::table("wxuser_device")->where($map)->find();
                                    if(empty($res)){
                                        Db::table('wxuser_device')->insert([
                                            "wxuser_id" =>$last_id,
                                            "deviceid" =>$info["id"],
                                            "create_time" =>time(),
                                            "update_time" =>time()
                                        ]);
                                    }
                                }


                                echo "第".$j."行-".$i."导入成功，微信用户表第:".$j."条！<br/>";
                            }else{
                                echo "第".$j."行-".$i."行导入失败！<br/>";
                            }
                        }

                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                    //
                }
                echo "结束";
            }else{
                $this->success('上传文件失败',url('userExcel'));
            }
        }else{
            return $this->fetch('user_excel');
        }
    }
    
     //导出房屋到Excel
    public function userExportExcel(){
        $com = $this->pidTokenId();
        $whe['id'] = array('in',$com['community_id']);
       
        $community_id = $com['community_id'];
        
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $userlist =  Db::name('wxuser')->where('id', 'in', $id)->select();;
            if(count($userlist) != count($id)){
                return json(['error' => '用户信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $whe['community_id'] = array('in',$com['community_id']);
            
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
           
            $userlist = Db::name('wxuser')->where('community_id', 'in', $community_id)->where($where)->order('id asc')->select();
            if(empty($userlist)){
                return json(['error' => '没有用户数据']);
            }
        }
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '小区名称')
            ->setCellValue('B1', '组团')
            ->setCellValue('C1', '楼栋')
            ->setCellValue('D1', '单元')
            ->setCellValue('E1', '房号')
            ->setCellValue('F1', '楼层号')
            ->setCellValue('G1', '姓名')
            ->setCellValue('H1', '绑定码')
        ;

        $count = Db::name('wxuser')->where('community_id', 'in', $community_id)->where($where)->count();  //计算有多少条数据
        for ($i=2; $i <= $count+1; $i++) {
            //根据小区ID查询小区名称
           
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $userlist[$i-2]["community_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $userlist[$i-2]['group']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $userlist[$i-2]["building"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $userlist[$i-2]["unit"]);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $userlist[$i-2]["room"]);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $userlist[$i-2]["wiegand"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $userlist[$i-2]["name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $userlist[$i-2]["bind_code"]);

            
        }
        $objPHPExcel->getActiveSheet()->setTitle('用户信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="用户信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
}